About the project

This course is to give the understanding of open data, open science, and open research tools.

First exercise

I am feeling confused and a bit stressed. But also excited as well.

My expectations are:

Then just a couple of lists to learn to make the lists:

  1. Item
    1. Item
    2. Item 2
      1. Item 3

I heard from this course from my colleague.

Here is the link to my github repository https://github.com/tiinasip/IODS-project

And here is the link to my diary https://tiinasip.github.io/IODS-project/

Another way to add the link to my diary


Exercise 2

Work summary I have went through Data camp parts R short and sweet and Regression and model validation. I have also listened a couple of statistics classes from YouTube and went through the chapters 3 & 4 from Kimmo’s textbook.

I have learned some basics in R and refreshed my knowledge about regression analysis.

Code for data creation is available at https://github.com/tiinasip/IODS-project/blob/master/data/create_learning2014.R

Code for data analysis (although it is thoroughly described in this report) https://github.com/tiinasip/IODS-project/blob/master/Exercise2_AnalysisPart.R

Data analysis

Data was collected in a survey for students attending statistics course. The aim was to find out, which factors have effect on course success. Originally there were many questions that were now grouped to be strategic, surface and deep questions.

Analysis starts with reading the data and taking the summary:

learnings2 <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/learning2014.txt ", sep=",", header=TRUE)
dim(learnings2)
str(learnings2)
summary(learnings2)
dim(learnings2)
## [1] 166   7
str(learnings2)
## 'data.frame':    166 obs. of  7 variables:
##  $ gender  : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
##  $ age     : int  53 55 49 53 49 38 50 37 37 42 ...
##  $ attitude: num  3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
##  $ deep    : num  3.58 2.92 3.5 3.5 3.67 ...
##  $ stra    : num  3.38 2.75 3.62 3.12 3.62 ...
##  $ surf    : num  2.58 3.17 2.25 2.25 2.83 ...
##  $ points  : int  25 12 24 10 22 21 21 31 24 26 ...
summary(learnings2)
##  gender       age           attitude          deep            stra      
##  F:110   Min.   :17.00   Min.   :1.400   Min.   :1.583   Min.   :1.250  
##  M: 56   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333   1st Qu.:2.625  
##          Median :22.00   Median :3.200   Median :3.667   Median :3.188  
##          Mean   :25.51   Mean   :3.143   Mean   :3.680   Mean   :3.121  
##          3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083   3rd Qu.:3.625  
##          Max.   :55.00   Max.   :5.000   Max.   :4.917   Max.   :5.000  
##       surf           points     
##  Min.   :1.583   Min.   : 7.00  
##  1st Qu.:2.417   1st Qu.:19.00  
##  Median :2.833   Median :23.00  
##  Mean   :2.787   Mean   :22.72  
##  3rd Qu.:3.167   3rd Qu.:27.75  
##  Max.   :4.333   Max.   :33.00

There are 166 rows and 7 variables/columns. 7 variables are: gender, age, attitude, deep, stra, surf and points. Gender is factor (male/female), age and points are integer, attiture, deep , stra and surf are numeric.

Medians and means seem to be quite close to each other, which is one indication of normal distribution but does not confirm it alone.

pairs(learnings2[-1],col = learnings2$gender, main="Graphical summary")

The scatter plot shows low correlations to other combinations thant points and attitude. For instance, stra and surf seem to have no correlations as the points are distributed widely. There is no clear positive, negative or curved correlation clearly visible in the figure.

Analysis is continued with a more detailed graphical analysis of variables. First without gender graphical summary.

library(GGally)
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
library(ggplot2)
 ggpairs(learnings2, mapping = aes(), title="Scatter plot matrix, no gender as column ",lower = list(combo = wrap("facethist", bins = 20)))

And then by gender

# create a more advanced plot matrix with ggpairs()
ggpairs(learnings2, mapping = aes(col=gender, alpha = 0.3), title="Graphical summary and gender ",
             lower = list(combo = wrap("facethist", bins = 20))
        )

#Distributions Age distribution is right-tailed, deep is left-tailed, especially for males. Strategic distribution is approximately symmetrical, especially for males. Surface is also quite symmetric. Attitude is interesting. When both genders are in, it looks quite symmetric. But for males it is left-tailed Points are bimodally distributed or for males even multimodal. Gender is nominal measurement meaning the categories are mutually exclusive and have no logical order.

If the correlation is between +/- 0.5 and +/-1, the correlation could be strong. Only points and attitude correlation (0.437) is close to that, which indicates that they have the strongest connection in the data and other variables are not that meaningful. The second highest correlation is between surf and deep, but it is -0.324.

#Regression Three variables selected as explanatory are: - Attitude - Strategic - Surface They were selected, because they had highest absolute correlations (0,437,0,146 and 0,144) with the points, which is our target variable.

First the model with only attitude

qplot(attitude, points, data = learnings2) + geom_smooth(method = "lm")

my_model <- lm(points ~ attitude, data = learnings2)
summary(my_model)
## 
## Call:
## lm(formula = points ~ attitude, data = learnings2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.6372     1.8303   6.358 1.95e-09 ***
## attitude      3.5255     0.5674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09
my_model <- lm(points ~ attitude, data = learnings2)
results <- summary(my_model)

P values of both intercept and attitude are under 0.05 indicating significant statistic correlation. T value is >2 indicating that as well.

Validation of graphical model is below. Normal Q-Q shows that both attitude and points seem to come from the same distribution, forming a line that’s roughly straight. It seems that the variables are normally distributed, although some pairs both at the beginning and at the end are not following the line.

Residuals vs. fitted tests, if the relationship of the variables is linear. If the plot is relatively shapeless, there are no obvious outliers and the data is generally symmetrically around 0 line, it is indicating linearity. In this case the plot is quite good as there is no pattern. There are some outliers, but not many and the values are around 0.

plot(my_model, which=c(1,2,5))

Also residuals vs. leverage figure indicates that there are no significant outliers. There are no many points in outside Cook’s distance line meaning there are not outliers that would change the regression result if I exclude those cases.

Next step is to add stra to the model and check the summary.

my_model2 <- lm(points ~ attitude + stra, data = learnings2)
summary(my_model2)
## 
## Call:
## lm(formula = points ~ attitude + stra, data = learnings2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.6436  -3.3113   0.5575   3.7928  10.9295 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   8.9729     2.3959   3.745  0.00025 ***
## attitude      3.4658     0.5652   6.132 6.31e-09 ***
## stra          0.9137     0.5345   1.709  0.08927 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.289 on 163 degrees of freedom
## Multiple R-squared:  0.2048, Adjusted R-squared:  0.1951 
## F-statistic: 20.99 on 2 and 163 DF,  p-value: 7.734e-09

Third model is created by adding both stra and surf to the first model and check if the model is improved.

my_model3 <- lm(points ~ attitude + stra + surf, data = learnings2)
summary(my_model3)
## 
## Call:
## lm(formula = points ~ attitude + stra + surf, data = learnings2)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.1550  -3.4346   0.5156   3.6401  10.8952 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.0171     3.6837   2.991  0.00322 ** 
## attitude      3.3952     0.5741   5.913 1.93e-08 ***
## stra          0.8531     0.5416   1.575  0.11716    
## surf         -0.5861     0.8014  -0.731  0.46563    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.296 on 162 degrees of freedom
## Multiple R-squared:  0.2074, Adjusted R-squared:  0.1927 
## F-statistic: 14.13 on 3 and 162 DF,  p-value: 3.156e-08

The second model with attitude and stra does not seem to create the model better. Stra’s p value is >0.05 meaning it is not statistically significant and could be dropped from the model.

The third model with attitude, stra and surf ends up to the same conclusion. Both stra and surf have p value >0.05 meaning they could be dropped from the model.It is adviced that one should choose the simple model when adding the variables does not improve the model.

But when the adjusted R-squares are checked, the situation changes. The adjusted R-squared compares the explanatory power of regression models that contain different numbers of predictors. Adjusted R-square of the model is 0.1856. The second model has adjusted R-square 0.1951. The third model has adjusted R-squared 0.1927. However, all these adjusted R values are low. Adjusted R-square tells the proportion of the variability in the dependent variable that is explained by the model.

I check still the diagnostics of model 2 regressio, but their output is very similar to the diagnostics of the first model.

plot(my_model2, which=c(1,2,5))

It is generally advisable to use simpler model when possible. As additional coefficients did not create clearly better model, I would use the simple points ~ attitude model.


Exercise 3

Work summary

Code for data creation is available at https://github.com/tiinasip/IODS-project/blob/master/data/create_alc.R

Code for data analysis (although it is thoroughly described in this report) https://github.com/tiinasip/IODS-project/blob/master/data/alc_analysis.R

Data analysis

Data is about student achievent in seconday education of two Portuguese schools.The data attributes include student grades, demographic, social and school related features) and it was collected by using school reports and questionnaires. The purpose of the analysis to find relationships between high or low alcohol consumption and other variables available.

Analysis starts with reading the data and taking the summary:

alc <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/alc.txt", sep=",", header=TRUE)
dim(alc)
str(alc)
summary(alc)
library(GGally)
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:GGally':
## 
##     nasa
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr)
gather(alc) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free")+geom_bar()
## Warning: attributes are not identical across measure variables;
## they will be dropped

Choosing the interesting variables

  • higher: wants to take higher education (binary: yes or no). My hypothesis is that students targeting to higher education are less likely to use a lot of alcohol.
  • romantic:with a romantic relationship (binary: yes or no). My hypothesis is that students having a romantic relationship are less likely to use a lot of alcohol.
  • gender. My hypothesis is that male students are more likely to use a lot of alcohol than female students.
  • activities: extra-curricular activities (binary: yes or no).My hypothesis is that students having activities are less likely to use a lot of alcohol.
  • weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours). My hypothesis is that students using more time (value 3 or 4) to study are less likely using a lot of alcohol.

Gender

alc_gender <- ggplot(alc, aes(x = high_use, y = G3, col=sex))
alc_gender + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and sex, outliers green")

There are some outliers, which are coloured green.Next check the crosstables between gender and high use.

alc_gender_table <-table(alc$sex,alc$high_use)
prop.table(alc_gender_table,2) #based on column totals
##    
##         FALSE      TRUE
##   F 0.5814815 0.3660714
##   M 0.4185185 0.6339286
prop.table(alc_gender_table,1) #based on row totals
##    
##         FALSE      TRUE
##   F 0.7929293 0.2070707
##   M 0.6141304 0.3858696
g1_ge <- ggplot(data = alc, aes(x = high_use, fill=sex))
g1_ge + geom_bar()+ggtitle("Gender and high alcohol use")

Gender in the data follows binomial distribution. 63 % of high users are males.Also the percentage of high users is higher for males (39%) than females (21%)

Higher education target

alc_higher <- ggplot(alc, aes(x = high_use, y = G3, col=higher))
alc_higher + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and higher education")

alc_higher_table <-table(alc$higher,alc$high_use)
prop.table(alc_higher_table,2) #based on column totals
##      
##            FALSE       TRUE
##   no  0.03333333 0.08035714
##   yes 0.96666667 0.91964286
prop.table(alc_higher_table,1) #based on row totals
##      
##          FALSE     TRUE
##   no  0.500000 0.500000
##   yes 0.717033 0.282967
g1_hi <- ggplot(data = alc, aes(x = high_use, fill=higher))
g1_hi + geom_bar()+ggtitle("Higher education target and high alcohol use")

Higher education target follows binomial distribution.8 % of high users are not targetting higher indicating that higher education target may not explain much of high use. Also the percentage of high use is only 50 % for students not targeting higher education.

Romantic relationship

alc_romantic <- ggplot(alc, aes(x = high_use, y = G3, col=romantic))
alc_romantic + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and romantic relationship")

alc_romantic_table <-table(alc$romantic,alc$high_use)
prop.table(alc_romantic_table,2) #based on column totals
##      
##           FALSE      TRUE
##   no  0.6740741 0.7053571
##   yes 0.3259259 0.2946429
prop.table(alc_romantic_table,1) #based on row totals
##      
##           FALSE      TRUE
##   no  0.6973180 0.3026820
##   yes 0.7272727 0.2727273
g1_ro <- ggplot(data = alc, aes(x = high_use, fill=romantic))
g1_ro + geom_bar()+ggtitle("Romantic relationship and high alcohol use")

Romantic relationship ollows binomial distribution.71 % of high users are not in romantic relationship. However, the share of high user from students having romantic relationship is 27% and from students not having relationship 30%. It seems that romantic relationship may not explain much.

Studytime

alc$studytime <-as.factor(alc$studytime)
alc_studytime <- ggplot(alc, aes(x = studytime, y = G3, col=high_use))
alc_studytime + geom_boxplot(outlier.colour="red") + ylab("grade")+ggtitle("Student grades by alcohol consumption and weekly studytime")

alc_studytime_table <-table(alc$studytime,alc$high_use)
prop.table(alc_studytime_table,2) #based on column totals
##    
##          FALSE       TRUE
##   1 0.22222222 0.38392857
##   2 0.49259259 0.50892857
##   3 0.20000000 0.07142857
##   4 0.08518519 0.03571429
prop.table(alc_studytime_table,1) #based on row totals
##    
##         FALSE      TRUE
##   1 0.5825243 0.4174757
##   2 0.7000000 0.3000000
##   3 0.8709677 0.1290323
##   4 0.8518519 0.1481481
g1_st <- ggplot(data = alc, aes(x = studytime, fill=high_use))
g1_st + geom_bar()+ggtitle("Studytime and high alcohol use")

Studytime follows ordinal scale. The percentages of high users are highest in studytime groups 1 and 2 (38% and 51%, respectively). The share of high users in studytime group 1 is the highest (42%). Surprisingly, the highest median grade is among high users whose study a lot. But for non-high-users the highest median is in the studytime group 3. However, n is much lower in studytime groups 3 and 4, so individiual performance influences more.

Activities

alc_activities <- ggplot(alc, aes(x = high_use, y = G3, col=activities))
alc_activities + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and activities")

alc_activities_table <-table(alc$activities,alc$high_use)
prop.table(alc_activities_table,2) #based on column totals
##      
##           FALSE      TRUE
##   no  0.4518519 0.5267857
##   yes 0.5481481 0.4732143
prop.table(alc_activities_table,1) #based on row totals
##      
##           FALSE      TRUE
##   no  0.6740331 0.3259669
##   yes 0.7363184 0.2636816
g1_ac <- ggplot(data = alc, aes(x = high_use, fill=activities))
g1_ac + geom_bar()+ggtitle("Activities and high alcohol use")

Activities follow binomial distribution.53 % of high users are not doing activities. However, the share of high user from students having activities is 27% and from students not having activites 33%. It seems that activities may not explain much.

Logistig regression model

As a conclusion it seems that my chosen variables are not explaining much. Sex and studytime seem to be the srongest candidates. Next I create model.

# find the model with glm()
m <- glm(high_use ~ sex + higher+ romantic + activities + studytime, data = alc, family = "binomial")
summary(m)
## 
## Call:
## glm(formula = high_use ~ sex + higher + romantic + activities + 
##     studytime, family = "binomial", data = alc)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.2851  -0.8818  -0.6724   1.2023   2.1803  
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)   
## (Intercept)   -0.36148    0.56212  -0.643  0.52018   
## sexM           0.68577    0.25344   2.706  0.00681 **
## higheryes     -0.38258    0.51758  -0.739  0.45980   
## romanticyes   -0.07465    0.26167  -0.285  0.77541   
## activitiesyes -0.30089    0.24016  -1.253  0.21025   
## studytime2    -0.25227    0.27284  -0.925  0.35517   
## studytime3    -1.15983    0.45238  -2.564  0.01035 * 
## studytime4    -1.10844    0.59105  -1.875  0.06074 . 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 462.21  on 381  degrees of freedom
## Residual deviance: 432.87  on 374  degrees of freedom
## AIC: 448.87
## 
## Number of Fisher Scoring iterations: 4
#coefficients
coef(m)
##   (Intercept)          sexM     higheryes   romanticyes activitiesyes 
##   -0.36148480    0.68577438   -0.38258312   -0.07465366   -0.30089256 
##    studytime2    studytime3    studytime4 
##   -0.25227181   -1.15983304   -1.10843894

From model it is clear that only sex and studytime are significant in the model. For others Pr(>|z|) is more than 0.05. I had five hypothesis and two of them were true in the sample indicating that there is a relationship in the population. Other 3 hypothesis were rejected based on the sample.

Odds ratio greater than one means odds are getting larger. Only sex is more than one so it is increasing odds that the student is a high-user. Odds ratio less than one means odds are getting smaller. Studytime has the smallest odds ratio. Confidence interval of studytime is (0.47, 0.87) meaning it remains under 1. Respectively sex’s confidence interval remains clearly over 1 (1.21, 3.25). On the other hand, non-meaningful variables have confidence intervals having values below and above 1 indicating that odds ratio is not significant for decision making.

# compute odds ratios (OR)
OR <- coef(m) %>% exp
# compute confidence intervals (CI)
CI <-confint(m)%>% exp
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR, CI)
##                      OR      2.5 %    97.5 %
## (Intercept)   0.6966412 0.22877627 2.1168399
## sexM          1.9853086 1.21136731 3.2780894
## higheryes     0.6820972 0.24452974 1.9096568
## romanticyes   0.9280649 0.55145455 1.5424153
## activitiesyes 0.7401573 0.46121490 1.1844172
## studytime2    0.7770335 0.45603512 1.3317371
## studytime3    0.3135385 0.12224825 0.7335040
## studytime4    0.3300738 0.09000723 0.9651789

As higher, romantic and activities were not significant, a new model is created and used for prediction as instructed.

m2 <- glm(high_use ~ sex +  studytime, data = alc, family = "binomial")
summary(m2)
## 
## Call:
## glm(formula = high_use ~ sex + studytime, family = "binomial", 
##     data = alc)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.1060  -0.8527  -0.7405   1.2506   2.1042  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  -0.8246     0.2763  -2.985  0.00284 **
## sexM          0.6543     0.2460   2.659  0.00783 **
## studytime2   -0.3292     0.2658  -1.239  0.21540   
## studytime3   -1.2735     0.4439  -2.869  0.00412 **
## studytime4   -1.2025     0.5858  -2.053  0.04010 * 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 462.21  on 381  degrees of freedom
## Residual deviance: 435.28  on 377  degrees of freedom
## AIC: 445.28
## 
## Number of Fisher Scoring iterations: 4
#coefficients
coef(m2)
## (Intercept)        sexM  studytime2  studytime3  studytime4 
##  -0.8246325   0.6542694  -0.3292488  -1.2735443  -1.2025286

Odds ratios and confidence intervals of new model.

# compute odds ratios (OR)
OR <- coef(m2) %>% exp
# compute confidence intervals (CI)
CI <-confint(m2)%>% exp
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR, CI)
##                    OR      2.5 %    97.5 %
## (Intercept) 0.4383961 0.25246554 0.7477169
## sexM        1.9237365 1.19050659 3.1290488
## studytime2  0.7194640 0.42763809 1.2143282
## studytime3  0.2798380 0.11064760 0.6421976
## studytime4  0.3004336 0.08256457 0.8676192

Prediction

# predict() the probability of high_use
probabilities <- predict(m2, type = "response")
# add the predicted probabilities to 'alc'
alc <- mutate(alc, probability = probabilities)
# use the probabilities to make a prediction of high_use
alc <- mutate(alc, prediction = probability>0.5)
# see the last ten original classes, predicted probabilities, and class predictions
select(alc, sex, studytime, high_use, probability, prediction) %>% tail(10)
##     sex studytime high_use probability prediction
## 373   M         1    FALSE   0.4575119      FALSE
## 374   M         1     TRUE   0.4575119      FALSE
## 375   F         3    FALSE   0.1092742      FALSE
## 376   F         1    FALSE   0.3047812      FALSE
## 377   F         3    FALSE   0.1092742      FALSE
## 378   F         2    FALSE   0.2397809      FALSE
## 379   F         2    FALSE   0.2397809      FALSE
## 380   F         2    FALSE   0.2397809      FALSE
## 381   M         1     TRUE   0.4575119      FALSE
## 382   M         1     TRUE   0.4575119      FALSE

Binary predictions in figure:

#a plot of 'high_use' versus 'probability' in 'alc'
g <- ggplot(alc, aes(x = probability, y = high_use, col=prediction))
g+geom_point(aes(col=prediction))

The model predict correctly in 270 cases of non-users. But the model did not predict any high-users at all. The same prediction power is just always guess that the student is not a high-user, and it is actually a relevant idea compared to the bad model, because 71 % of students in the survey were not high-users.

# tabulate the target variable versus the predictions
table(high_use = alc$high_use, prediction = alc$prediction)
##         prediction
## high_use FALSE
##    FALSE   270
##    TRUE    112
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
##         prediction
## high_use     FALSE       Sum
##    FALSE 0.7068063 0.7068063
##    TRUE  0.2931937 0.2931937
##    Sum   1.0000000 1.0000000

Analysis by models have advantages over guessing. In this case guessing produced good candidates, but the analysis showed their weaknesses. On the other hand, there were probably many other variables which had had significance but I did not take them into analysis because of my prejudices.


Exercise 4

Work summary

Codes are available at

Data load and description

Boston dataset contains information collected by the U.S Census Service concerning housing valuesin the area of Boston Mass. It was obtained from the StatLib archive. More information about each variable can be found in here

Descriptions of variables are:

  • CRIM: Per capita crime rate by town
  • ZN Proportion of residential land zoned for lots over 25,000 sq. ft
  • INDUS: Proportion of non-retail business acres per town
  • CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
  • NOX: Nitric oxide concentration (parts per 10 million)
  • RM: Average number of rooms per dwelling
  • AGE: Proportion of owner-occupied units built prior to 1940
  • DIS: Weighted distances to five Boston employment centers
  • RAD: Index of accessibility to radial highways
  • TAX: Full-value property tax rate per $10,000
  • PTRATIO: Pupil-teacher ratio by town
  • B: 1000(Bk — 0.63)², where Bk is the proportion of [people of African American descent] by town
  • LSTAT: Percentage of lower status of the population
  • MEDV: Median value of owner-occupied homes in $1000s
library(MASS)
data("Boston")
dim(Boston)
## [1] 506  14
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

According to the information the Boston data frame has 506 rows and 14 columns. That is equal to my check. All variables are either numeric or int. There is no missing values either:

sum(is.na(Boston))
## [1] 0
mean(is.na(Boston))
## [1] 0

From graphical overview it is easy to notice at least the following:

  • rm & medv, nox & indus, age & nox, tax & indus have positive correlation
  • dis & indus, dis & nox, dis & age, lstat & medv have negative correation
  • medv and rm seem to fit linear distribution
  • age and black are left-tailed
  • crim, dis are right-tailed
  • tax, rad and indus are bimodally distributed
  • lstat, nox and dis are skewed to the left
  • variable chas seems a little odd. However,Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) can be only 0 or 1 and therefore it is different from other variables.
library(GGally)
library(ggplot2)

ggpairs(Boston, title=“Scatter plot matrix, distributions”,lower = list( continuous = “smooth”,mapping = aes()))

Scatter plot matrix

Scatter plot matrix

pairs(Boston[-1], main="Graphical summary")

Standardization and crime rate variable

Scaling targets to normalising:

boston_scaled <- scale(Boston)
summary(boston_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865

When summary of scaled data is compared to the summary of the original data, it is obvious that magnitudes of min and max values have decreased and mean is always 0. For instance, max of lstat was 37.97 and after scaling 3.54, respectively black max 396.9 and 0.44. Zn min was 0, now -0.49, rm min was 3.56, now -3.88.

Next, categorial variable crim and its quantiles are calculated:

# change the object to data frame, because vector otherwise causes an error in next phase
boston_scaled<-as.data.frame(boston_scaled)
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

Testing and training sets are created:

# number of rows in the Boston dataset 
n <- nrow(boston_scaled)
# randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)
# creating train set
train <- boston_scaled[ind,]
# create testing set 
test <- boston_scaled[-ind,]
# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)

LDA

Classification method LDA is used to findthe variables that separate the classes best and predict the classes of new data. In order to work, the variables should be normally distributed and each variable should have the same variance. Therefore scaled boston data is used. LDA model is created below and Crime is the target variable.

lda.fit <- lda(crime~., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2425743 0.2450495 0.2574257 0.2549505 
## 
## Group means:
##                  zn      indus         chas        nox         rm
## low       0.9351432 -0.8826736 -0.111631099 -0.8483802  0.3943976
## med_low  -0.1546176 -0.2686364  0.045820446 -0.5211792 -0.1565978
## med_high -0.3701526  0.1859276  0.295521928  0.4675615  0.1578306
## high     -0.4872402  1.0170891 -0.004759149  1.0554659 -0.4042492
##                 age        dis        rad        tax     ptratio
## low      -0.8527696  0.8514739 -0.6842073 -0.7234669 -0.44419411
## med_low  -0.2098925  0.2492898 -0.5480059 -0.4555828 -0.08397265
## med_high  0.4381617 -0.4221449 -0.4120549 -0.3004739 -0.43781300
## high      0.8017656 -0.8455755  1.6384176  1.5142626  0.78111358
##               black        lstat        medv
## low       0.3882279 -0.747331010  0.46252911
## med_low   0.3155245 -0.078014122 -0.01927245
## med_high  0.0801219  0.007784642  0.24128429
## high     -0.6334500  0.809477552 -0.61023752
## 
## Coefficients of linear discriminants:
##                 LD1         LD2          LD3
## zn       0.08691090  0.76978734 -0.862421744
## indus    0.07271032 -0.16441243  0.153981092
## chas    -0.07322733 -0.06924524  0.090196389
## nox      0.33989790 -0.64297921 -1.455567581
## rm      -0.12782148 -0.15709098 -0.188799109
## age      0.23127784 -0.28652491  0.029767332
## dis     -0.03435006 -0.19144131 -0.007800122
## rad      3.42086735  0.92820790 -0.168313826
## tax      0.05504476 -0.10145793  0.639685541
## ptratio  0.08728993  0.07347148 -0.262187040
## black   -0.10998911  0.04411618  0.112270243
## lstat    0.24418974 -0.41944134  0.412796953
## medv     0.25266270 -0.52159971 -0.150845695
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9493 0.0384 0.0123
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)

Prior probabilities tell how training observations fell to crime categories. All probabilities are around 25 %. Group means show the mean value of each group by each variable. Coefficients of linear discriminants provides the linear combinations that are used to form the LDA decision rule. For instance, 0.131033364 * zn + 0.047138924 * indus ….0.237478243 * medv is the rule for LD1. Index of accessibility to radial highways (rad) has the largest coefficient value meaning it contibutes most. Average number of rooms per dwelling (rm) has the smallest coefficient; bigger houses with more rooms tend to locate on areas of low crime rates.Fit between proportion of trace fit between group variants

Proportion of trace is the percentage separation that each of the discriminant achieves. LD1 achieves already 95 %, when LD2 and LD 3 have only 4 % and 1 %. This means that the first linear discrimination is already enough.

There is a LDA biplot below.The biplot visualizes how variable rad contributes a lot in LD1 and it is contributing a lot also in LD2. Variable nox contributes in LD1 positively and in LD2 negatively, which was also seen from coefficients. Zn contributes in LD2, but not much in LD1. Other variables are around zero and do not stand out.

# plot the lda results
plot(lda.fit, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit, myscale = 1)

lda.pred <- predict(lda.fit, newdata = test)

Next correct classes are saved and categorical variable is removed: correct_classes <- test$crime test <- dplyr::select(test, -crime)

Crime categories are cross tabulated by correct and predicted values. High values are well predicted. Lowest values were well predicted as well. Low med and high med categories have more incorrect predictions, but also for them most predictions went right.

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       19       7        3    0
##   med_low   10      14        3    0
##   med_high   2      12        6    2
##   high       0       0        0   24

Distances and kmeans

Boston dataset is reloaded again and the done modifications are not valid any more. Data is standardized by using scale function. Scaling was successfull, means are 0.

library(MASS)
data("Boston")
boston_scaled2 <- scale(Boston)
summary(boston_scaled2)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
class(boston_scaled2)
## [1] "matrix"
boston_scaled2<-as.data.frame(boston_scaled2)

Distances calculation:

dist_eu<- dist(boston_scaled2)
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970

Kmeans clustering and pairs are calculated, but the number of centers here is 4, which is just a guess what could be the optimal number.

km4 <-kmeans(boston_scaled2, centers = 4)
pairs(boston_scaled2, col = km4$cluster)

str(km4)
## List of 9
##  $ cluster     : Named int [1:506] 3 3 2 4 2 3 3 3 3 3 ...
##   ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
##  $ centers     : num [1:4, 1:14] 0.817 -0.334 -0.38 -0.412 -0.487 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:4] "1" "2" "3" "4"
##   .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
##  $ totss       : num 7070
##  $ withinss    : num [1:4] 1621 469 968 405
##  $ tot.withinss: num 3463
##  $ betweenss   : num 3607
##  $ size        : int [1:4] 161 53 207 85
##  $ iter        : int 4
##  $ ifault      : int 0
##  - attr(*, "class")= chr "kmeans"
km4
## K-means clustering with 4 clusters of sizes 161, 53, 207, 85
## 
## Cluster means:
##         crim         zn      indus        chas        nox         rm
## 1  0.8169331 -0.4872402  1.1178179 -0.05224272  1.1426751 -0.4990493
## 2 -0.3341857 -0.1369421 -0.5709571  0.91622949 -0.1349892  1.6538269
## 3 -0.3804858 -0.3461806 -0.2727872 -0.10115080 -0.3870847 -0.2886676
## 4 -0.4123980  1.8513293 -1.0969530 -0.22601024 -1.1375261  0.6170389
##          age        dis        rad        tax    ptratio      black
## 1  0.7974774 -0.8518372  1.2144828  1.2897916  0.5834327 -0.6578560
## 2  0.2338847 -0.3551230 -0.3794677 -0.6255348 -0.9607918  0.3197676
## 3 -0.1101296  0.1320396 -0.5929459 -0.5934010  0.0761018  0.2840658
## 4 -1.3881521  1.5133543 -0.6197663 -0.6078716 -0.6913384  0.3548885
##         lstat       medv
## 1  0.90418975 -0.7303013
## 2 -0.97018595  1.6944654
## 3 -0.08205528 -0.1459139
## 4 -0.90787355  0.6820708
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   3   3   2   4   2   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   3   3   3   4   4   4   3   3   3   3   3   3   3   3   3   3   4   4 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   4   4   4   4   4   3   3   3   3   4   4   4   4   3   3   3   3   3 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   3   3   3   3   3   3   3   3   4   3   4   3   3   3   3   3   3   2 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   3   3   3   3   3   3   3   2   2   2   3   3   3   3   3   3   3   3 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   3   1   1   1   3   3   3   3   1   1   1   1   1   1   1   1   1   1 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   2   3   1   2   2 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   2   2   3   3   2   3   3   3   3   3   3   3   3   3   3   3   2   2 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   2   3   2   2   3   3   2   4   4   4   4   4   4   4   4   4   4   4 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   4   4   4   4   4   4   4   3   3   3   3   3   3   3   3   3   3   3 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   3   3   3   2   2   3   2   3   2   2   2   2   2   3   3   2   2   2 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   2   3   2   2   4   4   4   3   4   4   3   3   4   3   4   4   4   4 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   4   4   4   4   4   2   2   2   2   2   2   2   2   3   2   2   2   3 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   3   3   3   2   2   4   2   2   4   4   2   4   2   4   4   4   4   4 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   4   4   4   4   4   3   3   3   3   3   4   4   4   4   4   4   4   3 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   2   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   3   3   3   3   3   3   3   4   4   3   3   3   3   3   3   3   3   4 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   3   4   4   3   3   4   4   4   4   4   4   4   4   4   1   1   1   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   1   1   1   1   2   1   1   1   1   2   2   1   1   1   1   1   1   1 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   1   1   1   1   1   1   1   3   3   3   3   3   3   3   3   3   3   3 
## 505 506 
##   3   3 
## 
## Within cluster sum of squares by cluster:
## [1] 1620.8992  469.1828  967.7955  404.7936
##  (between_SS / total_SS =  51.0 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"

Finding the optimal number of clusters is not irrelevant question and the textbook recommends the method to plot within-group sum of squares associated with the k-means solution for each number of groups. Then the “elbow” in the picture gives indication of the most useful solution. The plot below indicates that the elbow is in 2, after 2 the decrease is slower. However, even with 3 it is still significant but I choose to use 2.

set.seed(123)
# determine the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled2, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line', main="WGSS and groups in K-means solution")

Only 51 % total variance in data set that is explained by the first clustering with 4 clusters, which is not impressive. I checked how many clusters I should have to gain 80 % of total variance and it was 20. It is clear that it is too much, so I still keep 2 clusters, although the biggest decrease of variation ends at 2. In real-life I should check the correct number of clusters also by other methods, e.g. silhouette.

km <-kmeans(boston_scaled2, centers = 2)
pairs(boston_scaled2, col = km$cluster)

Cluster visualization with 2 clusters is clearer than the first guess of 4.

str(km)
## List of 9
##  $ cluster     : Named int [1:506] 1 1 1 1 1 1 1 1 1 1 ...
##   ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
##  $ centers     : num [1:2, 1:14] -0.389 0.724 0.262 -0.487 -0.615 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:2] "1" "2"
##   .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
##  $ totss       : num 7070
##  $ withinss    : num [1:2] 2686 1891
##  $ tot.withinss: num 4577
##  $ betweenss   : num 2493
##  $ size        : int [1:2] 329 177
##  $ iter        : int 1
##  $ ifault      : int 0
##  - attr(*, "class")= chr "kmeans"
km
## K-means clustering with 2 clusters of sizes 329, 177
## 
## Cluster means:
##         crim         zn      indus         chas        nox         rm
## 1 -0.3894158  0.2621323 -0.6146857  0.002908943 -0.5823397  0.2446705
## 2  0.7238295 -0.4872402  1.1425514 -0.005407018  1.0824279 -0.4547830
##          age        dis        rad        tax    ptratio      black
## 1 -0.4331555  0.4540421 -0.5828749 -0.6291043 -0.2943707  0.3282754
## 2  0.8051309 -0.8439539  1.0834228  1.1693521  0.5471636 -0.6101842
##        lstat       medv
## 1 -0.4530491  0.3532917
## 2  0.8421083 -0.6566834
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2   1   1   1 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2   2   2   1 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   1   1   2   1   1 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   1   1   2   1   2   1   1   2   2   1   1   1   1   1   1   1   1 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 505 506 
##   1   1 
## 
## Within cluster sum of squares by cluster:
## [1] 2686.045 1890.637
##  (between_SS / total_SS =  35.3 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"

The plot picture shows the groups are not equal size, one is 177 and other 329. There are some pairs, in which the grouping seems to work nicely; for instance medvd & lstat, lstat & nox,dis & nox and rm & nox. But for some pairs the groups are unclear, for instance rm&ptratio, age & ptratio, ptratio & lstat.

km <-kmeans(boston_scaled2, centers = 2)
str(km)
## List of 9
##  $ cluster     : Named int [1:506] 2 2 2 2 2 2 2 2 2 2 ...
##   ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
##  $ centers     : num [1:2, 1:14] 0.724 -0.389 -0.487 0.262 1.143 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:2] "1" "2"
##   .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
##  $ totss       : num 7070
##  $ withinss    : num [1:2] 1891 2686
##  $ tot.withinss: num 4577
##  $ betweenss   : num 2493
##  $ size        : int [1:2] 177 329
##  $ iter        : int 1
##  $ ifault      : int 0
##  - attr(*, "class")= chr "kmeans"

Bonus: K-means and LDA fitting

Start again with data reloading and scaling

library(MASS)
library(ggplot2)
library(tidyr)
library(cluster)
data("Boston")
boston_scaled3 <- scale(Boston)
boston_scaled3<-as.data.frame(boston_scaled3)

Number of clusters is selected to be 5 and clusters are target classess.

km_4 <-kmeans(boston_scaled3, centers = 5)
lda.fit2 <- lda(km_4$cluster ~., data = boston_scaled3)
lda.fit2
## Call:
## lda(km_4$cluster ~ ., data = boston_scaled3)
## 
## Prior probabilities of groups:
##          1          2          3          4          5 
## 0.25296443 0.21146245 0.31027668 0.09881423 0.12648221 
## 
## Group means:
##         crim         zn      indus       chas        nox         rm
## 1  1.0878724 -0.4872402  1.0149946 -0.1492947  1.0187219 -0.4210063
## 2 -0.3243708 -0.4822312  0.6185681  0.1324196  0.4947716 -0.5346882
## 3 -0.3981592 -0.1664810 -0.6090235 -0.2221749 -0.6655615 -0.1199301
## 4 -0.3103881 -0.1159242 -0.4991257  1.0662850 -0.0692028  1.6606848
## 5 -0.4142124  2.2796750 -1.1802049 -0.2108119 -1.1778698  0.7327381
##          age        dis        rad        tax    ptratio      black
## 1  0.7521154 -0.8135370  1.6596029  1.5294129  0.8057784 -0.7784115
## 2  0.7503783 -0.5640394 -0.5954711 -0.1985406  0.1042866  0.0419631
## 3 -0.6336330  0.5362710 -0.5817365 -0.7039306 -0.0756665  0.3655348
## 4  0.2630692 -0.4217934 -0.3042757 -0.5487050 -0.9864145  0.3028535
## 5 -1.4099114  1.5840638 -0.6588648 -0.5713854 -0.8296553  0.3533591
##        lstat        medv
## 1  0.8914421 -0.75669132
## 2  0.5669361 -0.49061591
## 3 -0.4149421  0.05516096
## 4 -0.9553010  1.76459824
## 5 -0.9664968  0.81972201
## 
## Coefficients of linear discriminants:
##                  LD1          LD2         LD3         LD4
## crim    -0.053751141  0.179074873  0.13780108 -0.07519738
## zn       0.062843967  1.465907935 -0.50908589  1.32076958
## indus   -0.179836757 -0.391770295 -0.40486479  0.39138090
## chas     0.230845551 -0.111364285  0.41752818  0.17516588
## nox      0.076978215 -0.081264681 -0.04255968  0.44218751
## rm      -0.111320904  0.164332062  0.59726088  0.22808090
## age     -0.048463133 -0.522072143  0.34421689  0.63414099
## dis      0.291886353  0.306401440 -0.21018069 -0.27013447
## rad     -4.160201638  1.135383393  0.44562029 -1.62967439
## tax      0.204066630  0.381083248 -0.11925476  1.00108406
## ptratio  0.009872979 -0.170859777 -0.22250511  0.33481849
## black    0.025657288  0.005723222 -0.01480980 -0.08944504
## lstat   -0.105055816 -0.045731798  0.14150418  0.39609928
## medv     0.351343258  0.268482029  0.88984740  0.30142226
## 
## Proportion of trace:
##    LD1    LD2    LD3    LD4 
## 0.7423 0.1680 0.0517 0.0381
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

Biplot drawing next:

plot(lda.fit2, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit2, myscale = 1)

Everytime the model is run again, the results change. But rad and zn are standing out, also chas every so often. Arrows for each variable point in the direction of increasing values of that variable.Rad increases meaning higher the value, the more meaningful it is in clustering where it is pointin. Otherwise all variables are around zero meaning they are not influencial

3D Bonus

I copied the lines from the instructions and did the package installation

model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

Then I tried plotting as instucted

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')

However, at this point I run into trouble with WebGL. In the help page the cube is rolling but I just did not succeed in R Studio.

Data wrangling for exercise 5

hd <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human_development.csv", stringsAsFactors = F)
gii <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/gender_inequality.csv", stringsAsFactors = F, na.strings = "..")
#checking the dimension
dim(hd)
## [1] 195   8
dim(gii)
## [1] 195  10
#checking the structure
str(hd)
## 'data.frame':    195 obs. of  8 variables:
##  $ HDI.Rank                              : int  1 2 3 4 5 6 6 8 9 9 ...
##  $ Country                               : chr  "Norway" "Australia" "Switzerland" "Denmark" ...
##  $ Human.Development.Index..HDI.         : num  0.944 0.935 0.93 0.923 0.922 0.916 0.916 0.915 0.913 0.913 ...
##  $ Life.Expectancy.at.Birth              : num  81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
##  $ Expected.Years.of.Education           : num  17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
##  $ Mean.Years.of.Education               : num  12.6 13 12.8 12.7 11.9 13.1 12.2 12.9 13 12.5 ...
##  $ Gross.National.Income..GNI..per.Capita: chr  "64,992" "42,261" "56,431" "44,025" ...
##  $ GNI.per.Capita.Rank.Minus.HDI.Rank    : int  5 17 6 11 9 11 16 3 11 23 ...
str(gii)
## 'data.frame':    195 obs. of  10 variables:
##  $ GII.Rank                                    : int  1 2 3 4 5 6 6 8 9 9 ...
##  $ Country                                     : chr  "Norway" "Australia" "Switzerland" "Denmark" ...
##  $ Gender.Inequality.Index..GII.               : num  0.067 0.11 0.028 0.048 0.062 0.041 0.113 0.28 0.129 0.157 ...
##  $ Maternal.Mortality.Ratio                    : int  4 6 6 5 6 7 9 28 11 8 ...
##  $ Adolescent.Birth.Rate                       : num  7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
##  $ Percent.Representation.in.Parliament        : num  39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
##  $ Population.with.Secondary.Education..Female.: num  97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
##  $ Population.with.Secondary.Education..Male.  : num  96.7 94.6 96.6 96.6 90.5 97 78.6 94.8 100 95.3 ...
##  $ Labour.Force.Participation.Rate..Female.    : num  61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
##  $ Labour.Force.Participation.Rate..Male.      : num  68.7 71.8 74.9 66.4 70.6 66.4 68.1 68.9 71 73.8 ...
summary(hd)
##     HDI.Rank        Country          Human.Development.Index..HDI.
##  Min.   :  1.00   Length:195         Min.   :0.3480               
##  1st Qu.: 47.75   Class :character   1st Qu.:0.5770               
##  Median : 94.00   Mode  :character   Median :0.7210               
##  Mean   : 94.31                      Mean   :0.6918               
##  3rd Qu.:141.25                      3rd Qu.:0.8000               
##  Max.   :188.00                      Max.   :0.9440               
##  NA's   :7                                                        
##  Life.Expectancy.at.Birth Expected.Years.of.Education
##  Min.   :49.00            Min.   : 4.10              
##  1st Qu.:65.75            1st Qu.:11.10              
##  Median :73.10            Median :13.10              
##  Mean   :71.07            Mean   :12.86              
##  3rd Qu.:76.80            3rd Qu.:14.90              
##  Max.   :84.00            Max.   :20.20              
##                                                      
##  Mean.Years.of.Education Gross.National.Income..GNI..per.Capita
##  Min.   : 1.400          Length:195                            
##  1st Qu.: 5.550          Class :character                      
##  Median : 8.400          Mode  :character                      
##  Mean   : 8.079                                                
##  3rd Qu.:10.600                                                
##  Max.   :13.100                                                
##                                                                
##  GNI.per.Capita.Rank.Minus.HDI.Rank
##  Min.   :-84.0000                  
##  1st Qu.: -9.0000                  
##  Median :  1.5000                  
##  Mean   :  0.1862                  
##  3rd Qu.: 11.0000                  
##  Max.   : 47.0000                  
##  NA's   :7
summary(gii)
##     GII.Rank        Country          Gender.Inequality.Index..GII.
##  Min.   :  1.00   Length:195         Min.   :0.0160               
##  1st Qu.: 47.75   Class :character   1st Qu.:0.2030               
##  Median : 94.00   Mode  :character   Median :0.3935               
##  Mean   : 94.31                      Mean   :0.3695               
##  3rd Qu.:141.25                      3rd Qu.:0.5272               
##  Max.   :188.00                      Max.   :0.7440               
##  NA's   :7                           NA's   :33                   
##  Maternal.Mortality.Ratio Adolescent.Birth.Rate
##  Min.   :   1.0           Min.   :  0.60       
##  1st Qu.:  16.0           1st Qu.: 15.45       
##  Median :  69.0           Median : 40.95       
##  Mean   : 163.2           Mean   : 49.55       
##  3rd Qu.: 230.0           3rd Qu.: 71.78       
##  Max.   :1100.0           Max.   :204.80       
##  NA's   :10               NA's   :5            
##  Percent.Representation.in.Parliament
##  Min.   : 0.00                       
##  1st Qu.:12.47                       
##  Median :19.50                       
##  Mean   :20.60                       
##  3rd Qu.:27.02                       
##  Max.   :57.50                       
##  NA's   :3                           
##  Population.with.Secondary.Education..Female.
##  Min.   :  0.9                               
##  1st Qu.: 27.8                               
##  Median : 55.7                               
##  Mean   : 54.8                               
##  3rd Qu.: 81.8                               
##  Max.   :100.0                               
##  NA's   :26                                  
##  Population.with.Secondary.Education..Male.
##  Min.   :  3.20                            
##  1st Qu.: 38.30                            
##  Median : 60.00                            
##  Mean   : 60.29                            
##  3rd Qu.: 85.80                            
##  Max.   :100.00                            
##  NA's   :26                                
##  Labour.Force.Participation.Rate..Female.
##  Min.   :13.50                           
##  1st Qu.:44.50                           
##  Median :53.30                           
##  Mean   :52.61                           
##  3rd Qu.:62.62                           
##  Max.   :88.10                           
##  NA's   :11                              
##  Labour.Force.Participation.Rate..Male.
##  Min.   :44.20                         
##  1st Qu.:68.88                         
##  Median :75.55                         
##  Mean   :74.74                         
##  3rd Qu.:80.15                         
##  Max.   :95.50                         
##  NA's   :11

Renaming the columns:

names(hd)[names(hd) == "Human.Development.Index..HDI."] <- "HDI"
names(hd)[names(hd) == "Expected.Years.of.Education"] <- "EYE"
names(hd)[names(hd) == "Life.Expectancy.at.Birth"] <- "LEB"
names(hd)[names(hd) == "Mean.Years.of.Education"] <- "MYE"
names(hd)[names(hd) == "Gender.Inequality.Index..GII."] <- "GII"
names(hd)[names(hd) == "Maternal.Mortality.Ratio"] <- "MMR"
names(hd)[names(hd) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(hd)[names(hd) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(hd)[names(hd) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(hd)[names(hd) == "GNI.per.Capita.Rank.Minus.HDI.Rank"] <- "GNIMinusHDIRank"
names(gii)[names(gii) == "Adolescent.Birth.Rate"] <- "ADBR"
names(gii)[names(gii) == "Expected.Years.of.Education"] <- "EYE"
names(gii)[names(gii) == "Life.Expectancy.at.Birth"] <- "LEB"
names(gii)[names(gii) == "Mean.Years.of.Education"] <- "MYE"
names(gii)[names(gii) == "Gender.Inequality.Index..GII."] <- "GII"
names(gii)[names(gii) == "Maternal.Mortality.Ratio"] <- "MMR"
names(gii)[names(gii) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(gii)[names(gii) == "Population.with.Secondary.Education..Male."] <- "SecEducMale"
names(gii)[names(gii) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(gii)[names(gii) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Female."] <- "LabForParFem"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Male."] <- "LabForParMale"
head(hd)
##   HDI.Rank     Country   HDI  LEB  EYE  MYE GNIncPerCap GNIMinusHDIRank
## 1        1      Norway 0.944 81.6 17.5 12.6      64,992               5
## 2        2   Australia 0.935 82.4 20.2 13.0      42,261              17
## 3        3 Switzerland 0.930 83.0 15.8 12.8      56,431               6
## 4        4     Denmark 0.923 80.2 18.7 12.7      44,025              11
## 5        5 Netherlands 0.922 81.6 17.9 11.9      45,435               9
## 6        6     Germany 0.916 80.9 16.5 13.1      43,919              11
head(gii)
##   GII.Rank     Country   GII MMR ADBR PerParliament SecEducFemal
## 1        1      Norway 0.067   4  7.8          39.6         97.4
## 2        2   Australia 0.110   6 12.1          30.5         94.3
## 3        3 Switzerland 0.028   6  1.9          28.5         95.0
## 4        4     Denmark 0.048   5  5.1          38.0         95.5
## 5        5 Netherlands 0.062   6  6.2          36.9         87.7
## 6        6     Germany 0.041   7  3.8          36.9         96.3
##   SecEducMale LabForParFem LabForParMale
## 1        96.7         61.2          68.7
## 2        94.6         58.8          71.8
## 3        96.6         61.8          74.9
## 4        96.6         58.7          66.4
## 5        90.5         58.5          70.6
## 6        97.0         53.6          66.4

Exercise 5

Work summary Codes are available at

Data wrangling

Data set is about human development indeces (HDI). United Nations Development Programme has collected it and it contains many indeces that can be used for evaluating nation’s development in human outcomes. Traditional economic GNI values alone do not describe the humanity of the state and therefore complementary measures are needed. Such measures are for instance life expectancy, population with secondary education (female/male) etc. More information about the HDI is found here

Data is loaded from the given address

human <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human1.txt", sep  =",", header = T)

Next I check the data structure and check that the variables are the same I expected.

str(human)
## 'data.frame':    195 obs. of  19 variables:
##  $ HDI.Rank      : int  1 2 3 4 5 6 6 8 9 9 ...
##  $ Country       : Factor w/ 195 levels "Afghanistan",..: 129 10 169 48 124 67 84 186 34 125 ...
##  $ HDI           : num  0.944 0.935 0.93 0.923 0.922 0.916 0.916 0.915 0.913 0.913 ...
##  $ Life.Exp      : num  81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
##  $ Edu.Exp       : num  17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
##  $ Edu.Mean      : num  12.6 13 12.8 12.7 11.9 13.1 12.2 12.9 13 12.5 ...
##  $ GNI           : Factor w/ 194 levels "1,096","1,123",..: 166 135 156 139 140 137 127 154 134 117 ...
##  $ GNI.Minus.Rank: int  5 17 6 11 9 11 16 3 11 23 ...
##  $ GII.Rank      : int  1 2 3 4 5 6 6 8 9 9 ...
##  $ GII           : num  0.067 0.11 0.028 0.048 0.062 0.041 0.113 0.28 0.129 0.157 ...
##  $ Mat.Mor       : int  4 6 6 5 6 7 9 28 11 8 ...
##  $ Ado.Birth     : num  7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
##  $ Parli.F       : num  39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
##  $ Edu2.F        : num  97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
##  $ Edu2.M        : num  96.7 94.6 96.6 96.6 90.5 97 78.6 94.8 100 95.3 ...
##  $ Labo.F        : num  61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
##  $ Labo.M        : num  68.7 71.8 74.9 66.4 70.6 66.4 68.1 68.9 71 73.8 ...
##  $ Edu2.FM       : num  1.007 0.997 0.983 0.989 0.969 ...
##  $ Labo.FM       : num  0.891 0.819 0.825 0.884 0.829 ...
names(human)
##  [1] "HDI.Rank"       "Country"        "HDI"            "Life.Exp"      
##  [5] "Edu.Exp"        "Edu.Mean"       "GNI"            "GNI.Minus.Rank"
##  [9] "GII.Rank"       "GII"            "Mat.Mor"        "Ado.Birth"     
## [13] "Parli.F"        "Edu2.F"         "Edu2.M"         "Labo.F"        
## [17] "Labo.M"         "Edu2.FM"        "Labo.FM"

Commas are replaced and GNI changed to numeric. I also check GNI is now really a numeric variable.

human$GNI <- as.numeric(human$GNI)
str(human$GNI)
##  num [1:195] 166 135 156 139 140 137 127 154 134 117 ...

Only required columns are kept and NA rows are removed by usin complete.cases, country name column is removed:

library(dplyr)
human <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human1.txt", sep  =",", header = T)
human$GNI <- as.numeric(human$GNI)
keep <- c("Country", "Edu2.FM", "Labo.FM", "Life.Exp", "Edu.Exp", "GNI", "Mat.Mor", "Ado.Birth", "Parli.F")
human <- select(human, one_of(keep))
data.frame(human[-1], comp = complete.cases(human))
##       Edu2.FM   Labo.FM Life.Exp Edu.Exp GNI Mat.Mor Ado.Birth Parli.F
## 1   1.0072389 0.8908297     81.6    17.5 166       4       7.8    39.6
## 2   0.9968288 0.8189415     82.4    20.2 135       6      12.1    30.5
## 3   0.9834369 0.8251001     83.0    15.8 156       6       1.9    28.5
## 4   0.9886128 0.8840361     80.2    18.7 139       5       5.1    38.0
## 5   0.9690608 0.8286119     81.6    17.9 140       6       6.2    36.9
## 6   0.9927835 0.8072289     80.9    16.5 137       7       3.8    36.9
## 7   1.0241730 0.7797357     80.9    18.6 127       9       8.2    19.9
## 8   1.0031646 0.8171263     79.1    16.5 154      28      31.0    19.4
## 9   1.0000000 0.8676056     82.0    15.9 134      11      14.5    28.2
## 10  0.9968520 0.8401084     81.8    19.2 117       8      25.3    31.4
## 11  0.9148148 0.7616580     83.0    15.4 180       6       6.0    25.3
## 12  0.9116162 0.7566372     84.0    15.6 155      NA       3.3      NA
## 13         NA        NA     80.0    15.0 181      NA        NA    20.0
## 14  0.9908362 0.8880707     82.2    15.8 141       4       6.5    43.6
## 15  0.9989990 0.8107715     80.7    16.2 126       8      25.8    23.5
## 16  0.9934498 0.9108527     82.6    19.0 121       4      11.5    41.3
## 17  0.8641975 0.6948682     81.9    16.9 119      27       2.2    16.3
## 18  0.9667812 0.8379161     82.4    16.0 115       2       7.8    22.5
## 19  1.0000000 0.7848297     81.7    13.9 157      11       8.3    28.3
## 20  1.0139860 0.6931818     83.5    15.3 122       6       5.4    11.6
## 21  0.9348613 0.8010118     80.8    16.3 133       6       6.7    42.4
## 22  0.9375000 0.8230519     82.2    16.0 123      12       5.7    25.7
## 23  1.0000000 0.8064993     81.4    15.7 136       4       4.1    30.3
## 24  1.0000000 0.8703125     80.8    17.1 125       4       9.2    42.5
## 25  0.9775510 0.8275316     80.4    16.8  99       7       0.6    27.7
## 26  0.9138167 0.7978723     82.6    17.3 116       4      10.6    38.0
## 27  0.8844720 0.6655462     83.1    16.0 118       4       4.0    30.1
## 28  1.0020060 0.7481698     78.6    16.4  98       5       4.9    18.9
## 29  0.8880597 0.7072000     80.9    17.6  93       5      11.9    21.0
## 30  1.0000000 0.8156749     76.8    16.5  94      11      16.8    19.8
## 31  0.9424779 0.6985392     78.8    14.5 177      27      23.0      NA
## 32  0.9302326 0.7876231     80.2    14.0 101      10       5.5    12.5
## 33  1.1305085 0.5319372     78.2    13.8  37       6       9.5     0.0
## 34  1.0040568        NA     81.3    13.5 138      NA        NA    50.0
## 35  0.9959799 0.7448980     76.3    15.1  96       7      15.9    18.7
## 36  0.9286550 0.7534669     77.4    15.5  90       3      12.2    22.1
## 37  0.9448568 0.8291233     73.3    16.4  92      11      10.6    23.4
## 38  0.8772379 0.5716440     80.6    14.4 100       9      18.2    13.0
## 39  0.8605974 0.2579821     74.3    16.3 153      16      10.2    19.9
## 40  0.9774306 0.6333333     76.3    17.9  85      69      54.4    36.8
## 41  1.1944444 0.5054348     77.0    13.3 165       8      27.6    17.5
## 42  0.9594241 0.6577540     81.7    15.2  83      22      55.3    15.8
## 43  0.9896266 0.8293051     80.9    16.3  95       8      12.6    31.3
## 44  0.9918946 0.7466667     75.2    15.4  89      14      12.1    10.1
## 45  1.1031128 0.4510932     76.6    14.4 124      22      13.8    15.0
## 46  0.9989899 0.8121302     74.2    15.2  86      13      13.5    18.0
## 47  0.9081197 0.7654110     77.3    14.8  65      13      12.7    25.8
## 48  0.9875666 0.5246691     74.4    14.7 185      14      14.5     1.5
## 49  0.8891235 0.7504363     76.2    15.2  46       7      15.2    17.3
## 50  0.9436009 0.7939778     71.3    15.7  59       1      20.6    30.1
## 51  0.9686486 0.7963738     70.1    14.7  87      24      25.7    14.5
## 52  0.8266200 0.3510896     76.8    13.6 120      11      10.6     9.6
## 53  0.9358696 0.7503852     74.7    14.2  61      33      31.0    12.0
## 54  1.0815109 0.7239583     77.2    15.5  64      14      58.3    11.5
## 55  1.0410959 0.8738966     75.4    12.6  84      37      28.5    16.7
## 56  0.9645749 0.8690629     69.4    15.0  81      26      29.9    20.1
## 57  1.0205245 0.8603133     75.6    15.4  34      52      48.4    19.6
## 58         NA        NA     76.1    14.0  79      NA      49.3    25.7
## 59  0.9717868 0.8118644     74.2    14.4  50       5      35.9    20.4
## 60         NA        NA     72.7    13.7  42      NA        NA    10.3
## 61  1.0821643 0.5990220     77.6    13.3  62      85      78.5    19.3
## 62  0.9130435 0.5880795     74.7    12.7  88      29       5.7    14.2
## 63  0.8517241 0.5876011     74.4    15.6  60      73      30.9    11.6
## 64  1.0045045        NA     73.1    13.4  91      NA      56.3    43.8
## 65  0.9802956 0.7019868     70.4    12.3  97      84      34.8    24.7
## 66  0.7934783 0.7307061     74.9    14.4  32      16      16.9    34.0
## 67  0.9428934 0.6200000     79.4    13.8 170      80      43.1    48.9
## 68  0.9566787 0.3286319     79.3    13.8  57      16      12.0     3.1
## 69  1.0039604 0.5898734     79.4    13.9  41      38      60.8    33.3
## 70  0.9201183 0.2255435     75.4    15.1  49      23      31.6     3.1
## 71  1.1141732 0.6452020     74.2    14.2  54     110      83.2    17.0
## 72  0.6500000 0.4152542     75.3    14.5  63      20      30.9    14.4
## 73  0.9515707 0.4600262     74.9    13.7 189      29      16.9     5.8
## 74  0.9191419 0.5644556     76.8    13.1  53      49      63.4    37.1
## 75  1.0419847 0.7351485     74.5    15.2  48      69      70.8     9.6
## 76  0.9676375 0.7523302     74.9    13.8 168      41      46.8    11.3
## 77         NA        NA     73.8    12.9  80      NA        NA     6.7
## 78  0.9620123 0.9037356     70.8    11.9  56      26      40.0    15.6
## 79         NA        NA     73.4    15.8  24      23      35.4    25.0
## 80  0.8853503 0.2342342     74.0    13.5  26      50      26.5    11.6
## 81  0.7230216 0.6385185     75.4    13.4  28       7      18.3    33.3
## 82  0.9562044 0.7952167     71.0    15.1 183      23      25.7    11.8
## 83  0.8612903 0.2105263     74.8    14.0  38      89      10.0    25.7
## 84  0.8517398 0.8080569     74.6    13.1  25      89      50.7    22.3
## 85  0.9306030 0.6854962     77.8    11.8 192      21      15.3    20.7
## 86  0.9894737 0.7465565     74.7    12.3 182      29      27.1    10.7
## 87  0.6432665 0.5951134     76.5    13.6 187       8      15.1    19.3
## 88  1.0177665 0.6614268     75.9    14.2  22      87      77.0    41.6
## 89         NA 0.8228346     75.1    12.6 188      34      56.3    20.7
## 90  0.8164117 0.8160920     75.8    13.1  35      32       8.6    23.6
## 91  0.9953488 0.5208333     70.0    15.7 173      59      42.8    14.0
## 92  1.0142687 0.8167388     69.4    14.6  23      68      18.7    14.9
## 93  0.8750000 0.7967782     74.4    13.5  40      26      41.0     6.1
## 94  1.2801724        NA     77.8    12.7 193      NA        NA    21.9
## 95  1.3245823 0.3926702     71.6    14.0  47      15       2.5    16.0
## 96  0.7114967 0.3540197     74.8    14.6  20      46       4.6    31.3
## 97  1.0233813 0.7001255     74.0    13.5  30      83      68.5    20.9
## 98         NA 0.7141026     72.9    13.4 191      45      54.5    13.0
## 99  1.0541311 0.7912553     75.7    12.4 172      80      70.1    16.7
## 100 0.9909400 0.7171582     72.8    14.7 142     120      18.1     0.0
## 101 1.0079156 0.5978129     70.0    13.6 174      45      71.4    13.3
## 102 1.0470810 0.6526718     73.5    13.1  29     100      99.6    19.1
## 103 0.9469214 0.5886628     71.1    12.7  51     130      35.2    11.8
## 104 0.8348624 0.7251613     76.8    13.0  33      31       4.2     5.9
## 105 1.0716667 0.4023973     73.4    12.9 145      58      28.3     6.1
## 106 0.9448010 0.8811275     64.5    12.5  58     170      44.2     9.5
## 107 0.9689441 0.8506787     71.6    11.9 144      21      29.3    20.8
## 108 0.7244224 0.3168449     71.1    13.5  21      45      43.0     2.2
## 109        NA 0.6098830     65.6    10.8  39      61      18.0    25.8
## 110 1.4930748 0.8593272     64.4    12.5  55     240     103.0    16.2
## 111 0.8109756 0.6104513     68.9    13.0 190     190      48.3    17.1
## 112 0.8558140 0.6568396     72.9    11.9 175     110      67.0    16.8
## 113 0.9074074 0.2319277     72.9    13.0 131      NA      45.8      NA
## 114        NA 0.6362434     68.4    11.5 150      36      38.8    16.4
## 115 1.0345369 0.6411543     68.2    11.3 176     120      46.8    27.1
## 116 0.8440367 0.6050633     73.0    12.3 171      69      76.0    27.4
## 117 0.9578393 0.7355372     57.4    13.6  31     140      50.9    40.7
## 118 0.8342697 0.8880779     75.8    11.9 143      49      29.0    24.3
## 119 0.8054146 0.7935723     68.3    13.2 152     200      71.9    51.8
## 120 0.9762397 0.7044025     70.6    12.5 102      75      29.3    23.3
## 121 0.5537849 0.2134670     69.4    10.1  43      67      68.7    26.5
## 122        NA 0.6152927     73.3    13.5 160      53      70.6    20.8
## 123        NA        NA     69.1    11.7 108      96      18.6     0.0
## 124 1.2615063 0.5291925     66.4    10.3 161     250      88.5    31.3
## 125 1.0287206 0.5902864     74.9    11.5 128     100     100.8    39.1
## 126 0.6854305 0.3496042     74.0    11.6 163     120      35.8    11.0
## 127 0.9680233 0.8587127     64.8    11.3 186     130      54.9    37.7
## 128 0.9439655 0.5589569     71.8    10.7 164     140      97.2    13.3
## 129 1.0427632 0.7639429     69.4    11.2  73      44      42.8    15.2
## 130 0.4770318 0.3379224     68.0    11.7 148     190      32.8    12.2
## 131 1.0852713 0.5162847     73.1    11.1 114     120      84.0    25.8
## 132 0.9855072 0.8639896     69.5    12.6 169     120      40.9     8.3
## 133        NA 0.4842520     68.2    11.7 147     270      52.2    38.5
## 134 0.7283951 0.1856946     69.6    12.3  74      49      41.6    12.4
## 135        NA 0.7687500     71.9    10.6  76      86      44.8     0.0
## 136 0.8446809 0.9383562     62.3    11.1 159     410     126.7    11.5
## 137        NA        NA     66.0    12.3  71     130      16.6     8.7
## 138        NA 0.8752711     57.6     9.0  82     290     112.6    19.7
## 139 0.5863636 0.8539720     60.1    13.5 111     280     125.4    12.7
## 140 0.6986090 0.9425770     61.4    11.5 113     380      58.4    10.9
## 141 0.6189189 0.9646018     66.2    10.6 130      NA      65.0    25.0
## 142 0.8256659 0.6825208     71.6    10.0 104     170      80.6    20.0
## 143 0.4323144 0.9109827     68.4    10.9  78     170      44.3    19.0
## 144        NA 0.5822622     66.5    11.3  77     210      65.1    18.2
## 145 0.8057325 0.8591160     61.6    11.0  75     400      93.6    20.8
## 146 0.4633508 0.9173364     69.6    12.4  68     190      73.7    29.5
## 147 0.4186551 0.2967431     66.2     7.8 132     170      27.3    19.7
## 148 1.4967320 0.9137303     65.9     8.6 129     200      12.1     4.7
## 149        NA 0.8231469     52.3    11.4 162     460     170.2    36.8
## 150 0.8423077 0.6131285     49.0    11.3 149     310      72.0    14.7
## 151 0.5894737 0.9767184     65.0     9.2  70     410     122.7    36.0
## 152        NA 0.7566719     52.8     9.0 146     560     119.6     6.6
## 153 0.6103152 0.8307292     55.5    10.4  76     590     115.8    27.1
## 154        NA 0.9569061     65.1    10.3   5     440     122.8    20.5
## 155 0.7854839 0.9275362     57.5    10.9  15     470      60.3    35.1
## 156 0.3971292 0.3628319     63.1     8.5 110     320      73.3    22.2
## 157        NA 0.6759494     67.9     9.2  11     130      64.9     2.0
## 158 0.5241379 0.9527027     62.6     9.9  72     220      62.1     2.7
## 159        NA 0.4394507     63.3    11.5   8     350      51.1     3.0
## 160 0.3220974 0.3518006     63.8     9.2 109     270      47.0     0.7
## 161 1.1526316 0.8027211     49.8    11.1 106     490      89.4    26.8
## 162 0.3995037 0.9913899     59.7    12.2   4     450      91.5    17.6
## 163 0.6363636 0.8577465     62.8     8.7  16     380      42.0     3.5
## 164 0.9090909 1.0128957     64.2    10.3   9     320      33.6    57.5
## 165 0.6835821 0.9570707     58.5     9.8  14     360     126.6    35.0
## 166 0.4185185 0.8633461     59.6    11.1  17     340      90.2     8.4
## 167 0.6648352 0.4118421     63.5     7.0 112     360      84.0    23.8
## 168        NA 0.5361891     62.0     6.4 105     230      18.6    12.7
## 169        NA        NA     55.7     7.6  69     730      75.3    24.3
## 170 0.4675325 0.7500000     66.5     7.9  67     320      94.4    42.7
## 171 0.1979866 0.1987421     60.4     9.3  19     400      86.8    27.6
## 172 0.4651163 0.6437346     51.5     8.9 103     720     130.3     9.2
## 173 0.5138889 1.0380368     62.8    10.8 178     510     144.8    16.7
## 174 0.4285714 0.8756999     64.1     8.5   7     420      78.4    25.5
## 175 0.5523810 0.8709288     60.2     8.8  10     430     115.8     9.4
## 176 0.3950617 0.9658470     58.7     9.8 167     730     135.3     8.2
## 177 0.3918575 0.8981481     60.9     9.5 184     640     117.4    10.7
## 178        NA 0.8687898     55.2     9.0   6     560      99.3    13.7
## 179 0.5099338 0.6240786     58.0     8.4  12     550     175.6     9.5
## 180 0.2258065 1.0326087     55.1     9.3   2     480     137.8    39.6
## 181 0.4608295 0.9521739     50.9     8.6  18    1100     100.7    12.4
## 182        NA 0.8378033     58.8     8.7   1     650     131.0    21.9
## 183 0.2812500 0.8566667     58.7     7.8  13     400     115.4    13.3
## 184 0.6385542 1.0158537     56.7    10.1 179     740      30.3    34.9
## 185 0.1717172 0.8080808     51.6     7.4  66     980     152.0    14.9
## 186        NA 0.8908686     63.7     4.1   3     380      65.3    22.0
## 187 0.3782772 0.8531140     50.7     7.2 158     880      98.3    12.5
## 188 0.3076923 0.4459309     61.4     5.4 194     630     204.8    13.3
## 189 0.7289916 0.3081009     70.6    12.0  52     155      45.4    14.0
## 190 0.8250377 0.7884131     74.0    12.7  27      72      21.2    18.7
## 191 0.8784119 0.6514286     72.3    13.6  36      28      30.8    19.0
## 192 0.9836957 0.6729323     75.0    14.0  44      85      68.3    27.0
## 193 0.5329670 0.3711083     68.4    11.2 151     183      38.7    17.5
## 194 0.7015873 0.8537859     58.5     9.6 107     506     109.7    22.5
## 195 0.8333333 0.6558018     71.5    12.2  45     210      47.4    21.8
##      comp
## 1    TRUE
## 2    TRUE
## 3    TRUE
## 4    TRUE
## 5    TRUE
## 6    TRUE
## 7    TRUE
## 8    TRUE
## 9    TRUE
## 10   TRUE
## 11   TRUE
## 12  FALSE
## 13  FALSE
## 14   TRUE
## 15   TRUE
## 16   TRUE
## 17   TRUE
## 18   TRUE
## 19   TRUE
## 20   TRUE
## 21   TRUE
## 22   TRUE
## 23   TRUE
## 24   TRUE
## 25   TRUE
## 26   TRUE
## 27   TRUE
## 28   TRUE
## 29   TRUE
## 30   TRUE
## 31  FALSE
## 32   TRUE
## 33   TRUE
## 34  FALSE
## 35   TRUE
## 36   TRUE
## 37   TRUE
## 38   TRUE
## 39   TRUE
## 40   TRUE
## 41   TRUE
## 42   TRUE
## 43   TRUE
## 44   TRUE
## 45   TRUE
## 46   TRUE
## 47   TRUE
## 48   TRUE
## 49   TRUE
## 50   TRUE
## 51   TRUE
## 52   TRUE
## 53   TRUE
## 54   TRUE
## 55   TRUE
## 56   TRUE
## 57   TRUE
## 58  FALSE
## 59   TRUE
## 60  FALSE
## 61   TRUE
## 62   TRUE
## 63   TRUE
## 64  FALSE
## 65   TRUE
## 66   TRUE
## 67   TRUE
## 68   TRUE
## 69   TRUE
## 70   TRUE
## 71   TRUE
## 72   TRUE
## 73   TRUE
## 74   TRUE
## 75   TRUE
## 76   TRUE
## 77  FALSE
## 78   TRUE
## 79  FALSE
## 80   TRUE
## 81   TRUE
## 82   TRUE
## 83   TRUE
## 84   TRUE
## 85   TRUE
## 86   TRUE
## 87   TRUE
## 88   TRUE
## 89  FALSE
## 90   TRUE
## 91   TRUE
## 92   TRUE
## 93   TRUE
## 94  FALSE
## 95   TRUE
## 96   TRUE
## 97   TRUE
## 98  FALSE
## 99   TRUE
## 100  TRUE
## 101  TRUE
## 102  TRUE
## 103  TRUE
## 104  TRUE
## 105  TRUE
## 106  TRUE
## 107  TRUE
## 108  TRUE
## 109 FALSE
## 110  TRUE
## 111  TRUE
## 112  TRUE
## 113 FALSE
## 114 FALSE
## 115  TRUE
## 116  TRUE
## 117  TRUE
## 118  TRUE
## 119  TRUE
## 120  TRUE
## 121  TRUE
## 122 FALSE
## 123 FALSE
## 124  TRUE
## 125  TRUE
## 126  TRUE
## 127  TRUE
## 128  TRUE
## 129  TRUE
## 130  TRUE
## 131  TRUE
## 132  TRUE
## 133 FALSE
## 134  TRUE
## 135 FALSE
## 136  TRUE
## 137 FALSE
## 138 FALSE
## 139  TRUE
## 140  TRUE
## 141 FALSE
## 142  TRUE
## 143  TRUE
## 144 FALSE
## 145  TRUE
## 146  TRUE
## 147  TRUE
## 148  TRUE
## 149 FALSE
## 150  TRUE
## 151  TRUE
## 152 FALSE
## 153  TRUE
## 154 FALSE
## 155  TRUE
## 156  TRUE
## 157 FALSE
## 158  TRUE
## 159 FALSE
## 160  TRUE
## 161  TRUE
## 162  TRUE
## 163  TRUE
## 164  TRUE
## 165  TRUE
## 166  TRUE
## 167  TRUE
## 168 FALSE
## 169 FALSE
## 170  TRUE
## 171  TRUE
## 172  TRUE
## 173  TRUE
## 174  TRUE
## 175  TRUE
## 176  TRUE
## 177  TRUE
## 178 FALSE
## 179  TRUE
## 180  TRUE
## 181  TRUE
## 182 FALSE
## 183  TRUE
## 184  TRUE
## 185  TRUE
## 186 FALSE
## 187  TRUE
## 188  TRUE
## 189  TRUE
## 190  TRUE
## 191  TRUE
## 192  TRUE
## 193  TRUE
## 194  TRUE
## 195  TRUE
# filter out all rows with NA values
human_ <- filter(human, complete.cases(human))
tail(human_,10)
##                             Country   Edu2.FM   Labo.FM Life.Exp Edu.Exp
## 153                            Chad 0.1717172 0.8080808     51.6     7.4
## 154        Central African Republic 0.3782772 0.8531140     50.7     7.2
## 155                           Niger 0.3076923 0.4459309     61.4     5.4
## 156                     Arab States 0.7289916 0.3081009     70.6    12.0
## 157       East Asia and the Pacific 0.8250377 0.7884131     74.0    12.7
## 158         Europe and Central Asia 0.8784119 0.6514286     72.3    13.6
## 159 Latin America and the Caribbean 0.9836957 0.6729323     75.0    14.0
## 160                      South Asia 0.5329670 0.3711083     68.4    11.2
## 161              Sub-Saharan Africa 0.7015873 0.8537859     58.5     9.6
## 162                           World 0.8333333 0.6558018     71.5    12.2
##     GNI Mat.Mor Ado.Birth Parli.F
## 153  66     980     152.0    14.9
## 154 158     880      98.3    12.5
## 155 194     630     204.8    13.3
## 156  52     155      45.4    14.0
## 157  27      72      21.2    18.7
## 158  36      28      30.8    19.0
## 159  44      85      68.3    27.0
## 160 151     183      38.7    17.5
## 161 107     506     109.7    22.5
## 162  45     210      47.4    21.8
last <- nrow(human_) - 7
human_ <- human[1:last, ]
rownames(human_) <- human_$Country
#country names column removal
human_ <- select(human_, -Country)
dim(human_)
## [1] 155   8
human <-human_
str(human)
## 'data.frame':    155 obs. of  8 variables:
##  $ Edu2.FM  : num  1.007 0.997 0.983 0.989 0.969 ...
##  $ Labo.FM  : num  0.891 0.819 0.825 0.884 0.829 ...
##  $ Life.Exp : num  81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
##  $ Edu.Exp  : num  17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
##  $ GNI      : num  166 135 156 139 140 137 127 154 134 117 ...
##  $ Mat.Mor  : int  4 6 6 5 6 7 9 28 11 8 ...
##  $ Ado.Birth: num  7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
##  $ Parli.F  : num  39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...

Not all the rows are countries and therefore regions are taken out. The number of rows decreases to 155 and there are 8 variables as it should be.

Data analysis

Although my data wrangling part seemed to be successfull, I read the wrangled data set and name it to human2.

human2 <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human2.txt", sep  =",", header = T)
str(human2)
## 'data.frame':    155 obs. of  8 variables:
##  $ Edu2.FM  : num  1.007 0.997 0.983 0.989 0.969 ...
##  $ Labo.FM  : num  0.891 0.819 0.825 0.884 0.829 ...
##  $ Edu.Exp  : num  17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
##  $ Life.Exp : num  81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
##  $ GNI      : int  64992 42261 56431 44025 45435 43919 39568 52947 42155 32689 ...
##  $ Mat.Mor  : int  4 6 6 5 6 7 9 28 11 8 ...
##  $ Ado.Birth: num  7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
##  $ Parli.F  : num  39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...

Dimensions analysis

As catter plot matrix shows, Edu.Exp, Parli.F and Edu2.FM seem to be quite normally distributed. Ado.Birth, Mat.Mor and GNI are skewed to the right. Labo.FM is skewed to the left.

library(GGally)
library(ggplot2)
ggpairs(human2, mapping = aes(), title="Scatter plot matrix, distributions ",lower = list(combo = wrap("facethist", bins = 20)))

summary(human2)
##     Edu2.FM          Labo.FM          Edu.Exp         Life.Exp    
##  Min.   :0.1717   Min.   :0.1857   Min.   : 5.40   Min.   :49.00  
##  1st Qu.:0.7264   1st Qu.:0.5984   1st Qu.:11.25   1st Qu.:66.30  
##  Median :0.9375   Median :0.7535   Median :13.50   Median :74.20  
##  Mean   :0.8529   Mean   :0.7074   Mean   :13.18   Mean   :71.65  
##  3rd Qu.:0.9968   3rd Qu.:0.8535   3rd Qu.:15.20   3rd Qu.:77.25  
##  Max.   :1.4967   Max.   :1.0380   Max.   :20.20   Max.   :83.50  
##       GNI            Mat.Mor         Ado.Birth         Parli.F     
##  Min.   :   581   Min.   :   1.0   Min.   :  0.60   Min.   : 0.00  
##  1st Qu.:  4198   1st Qu.:  11.5   1st Qu.: 12.65   1st Qu.:12.40  
##  Median : 12040   Median :  49.0   Median : 33.60   Median :19.30  
##  Mean   : 17628   Mean   : 149.1   Mean   : 47.16   Mean   :20.91  
##  3rd Qu.: 24512   3rd Qu.: 190.0   3rd Qu.: 71.95   3rd Qu.:27.95  
##  Max.   :123124   Max.   :1100.0   Max.   :204.80   Max.   :57.50

Expected years of education and life expectancy are most strongly positively correlated.The strongest negative correlation is between maternal mortality ratio and life expectancy. On the other hand, gross national income & Labour Force Participation Rate (Female) and Population with Secondary Education (Female) & Labour Force Participation Rate (Female) seem not to correlate at all. This is clearly visible also in correlation matrix visualization

library(corrplot)
## corrplot 0.84 loaded
cor_matrix<-cor(human2)
corrplot(cor_matrix, method="circle", type="upper",cl.pos="b", tl.pos="d", tl.cex=0.6)

### PCA analysis

The first PCA is created with non-standardised data.

pca_human <- prcomp(human2)
s<-summary(pca_human)
pca_pr_nonst <- round(100*s$importance[2,], digits = 1)
pc_lab_nonst <- paste0(names(pca_pr_nonst), " (", pca_pr_nonst, "%)")
biplot(pca_human, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = pc_lab_nonst[1], ylab = pc_lab_nonst[2])

pca_pr_nonst
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8 
## 100   0   0   0   0   0   0   0

The picture difficult to interpret. GNI has the biggest variance here and it stands out. Printing out the variance percentages shows clearly how the PC1 seems to capture all the variance. Also the loading values are very large. However, next then the same is done with standardized data

human_std <- scale(human2)
pca_human2 <- prcomp(human_std)
s<-summary(pca_human2)
pca_pr <- round(100*s$importance[2,], digits = 1)
pc_lab <- paste0(names(pca_pr), " (", pca_pr, "%)")
biplot(pca_human2, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2])

pca_pr
##  PC1  PC2  PC3  PC4  PC5  PC6  PC7  PC8 
## 53.6 16.2  9.6  7.6  5.5  3.6  2.6  1.3

It is obvious that standardisation is required before PCA in this case. In fact, it is usually recommended, because PCA is sensitive to the relative scaling of the original features and assumes features with larger variance to be more important to those with smaller variance.

With standardization, GNI is no longer as strongly standing out but it is possible to see other variables as well. Gross National Income naturally creates very large numbers in comparison e.g. life-expectansy that is not usually over 80 years. Without standardisation GNI is overemphasized.

When standardized biplot is analysed, Labour Force Participation Rate (Female) and Percent Female Representation in Parliament have small angle and they are positively correlated meaning that the countries where females are active in labour force have them in the parliament as well. They also strongly contribute to PC2.

Maternal mortality ratio and Adolescent Birth Rate point to the same direction with small angle with each other. They are strongly positively correlated with each other. These components are also contributing to PC1. From the content perspective this is very logical. When girls are not educated - meaning families and the society are not investing in them - they are in higher risk to be married as children, and when they don’t have education, own income and status, their healthy needs are not seen important in the society.

The remaining variables show to the opposite direction. Those variables are Population with Secondary Education (Female), Expected Years of Education, Gross National Income (GNI) per Capita and Life Expectancy at Birth. They are positively correlated with each other and negatively correlated with maternal mortality ratio and adolescent birth rate. These components are also contributing negatively to PC1.

The correlation matrix confirms correlations.

cor_matrix<-round(cor(human2), digits=2)
cor_matrix
##           Edu2.FM Labo.FM Edu.Exp Life.Exp   GNI Mat.Mor Ado.Birth Parli.F
## Edu2.FM      1.00    0.01    0.59     0.58  0.43   -0.66     -0.53    0.08
## Labo.FM      0.01    1.00    0.05    -0.14 -0.02    0.24      0.12    0.25
## Edu.Exp      0.59    0.05    1.00     0.79  0.62   -0.74     -0.70    0.21
## Life.Exp     0.58   -0.14    0.79     1.00  0.63   -0.86     -0.73    0.17
## GNI          0.43   -0.02    0.62     0.63  1.00   -0.50     -0.56    0.09
## Mat.Mor     -0.66    0.24   -0.74    -0.86 -0.50    1.00      0.76   -0.09
## Ado.Birth   -0.53    0.12   -0.70    -0.73 -0.56    0.76      1.00   -0.07
## Parli.F      0.08    0.25    0.21     0.17  0.09   -0.09     -0.07    1.00
pca_human2
## Standard deviations (1, .., p=8):
## [1] 2.0708380 1.1397204 0.8750485 0.7788630 0.6619563 0.5363061 0.4589994
## [8] 0.3222406
## 
## Rotation (n x k) = (8 x 8):
##                   PC1         PC2         PC3         PC4        PC5
## Edu2.FM   -0.35664370  0.03796058 -0.24223089  0.62678110 -0.5983585
## Labo.FM    0.05457785  0.72432726 -0.58428770  0.06199424  0.2625067
## Edu.Exp   -0.42766720  0.13940571 -0.07340270 -0.07020294  0.1659678
## Life.Exp  -0.44372240 -0.02530473  0.10991305 -0.05834819  0.1628935
## GNI       -0.35048295  0.05060876 -0.20168779 -0.72727675 -0.4950306
## Mat.Mor    0.43697098  0.14508727 -0.12522539 -0.25170614 -0.1800657
## Ado.Birth  0.41126010  0.07708468  0.01968243  0.04986763 -0.4672068
## Parli.F   -0.08438558  0.65136866  0.72506309  0.01396293 -0.1523699
##                   PC6         PC7         PC8
## Edu2.FM    0.17713316  0.05773644  0.16459453
## Labo.FM   -0.03500707 -0.22729927 -0.07304568
## Edu.Exp   -0.38606919  0.77962966 -0.05415984
## Life.Exp  -0.42242796 -0.43406432  0.62737008
## GNI        0.11120305 -0.13711838 -0.16961173
## Mat.Mor    0.17370039  0.35380306  0.72193946
## Ado.Birth -0.76056557 -0.06897064 -0.14335186
## Parli.F    0.13749772  0.00568387 -0.02306476

In PC1 the most meaningful components are life expectancy to one direction and maternal mortality to the other direction. As a whole, the meaningful components in PC1 are referring life expectancy as a whole. When a woman’s life is valued, she is educated, given opportunites, taken caren of at labour and thus she lives longer.

In PC2 Labour Force Participation Rate (Female) and Percent Female Representation in Parliament are the most meaningful components.These metrics could be grouped as “Women attendance rate in society”. PC1 explains 53,6 % and PC2 16,2%. In other words, factors related to the life excpectancy explain the most and factors related to women attendance rate in the society covers about 16 %. Next groupings are under 10 %.

Tea set

The data used here is based on a questionnaire on tea. 300 individuals were asked how they drink tea (18 questions), what are their product’s perception (12 questions) and some personal details (4 questions).

The tea set data is loaded. There are 300 rows and 36 variables. Breakfast, tea time, evening, lunch, dinner, always, home, work, tearoom, friends, resto, pub, sugar, sex, escape, spirituality, healthy, diuretic, friendliness, iron, feminine, sophisticated, slimming, exciting, relaxing, effect on health and sport have two options (being binary), other variables have more. Only price and age are continous.

#install.packages("FactoMineR")
library(FactoMineR)
library(dplyr)
library(MASS)
library(tidyr)
library(stringr)
tea_time <-tea
summary(tea_time)
str(tea_time)
dim(tea_time)
str

str

keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch","where","price","lunch","friends","friendliness")
tea_time2 <- select(tea, keep_columns)
mca_tea <- MCA(tea_time2, graph = FALSE)
summary(mca_tea)
print(mca_tea)
summary

summary

MCA graphs and factor map are created

mca_tea <- MCA(tea_time2, graph = TRUE)
plot(mca_tea, invisible=c("ind"))

Closer look to eigenvalues shows that the first MCA dimension covers almost 12% of variance and 6 dimensions reach over 50 %.

library(factoextra)
eig.val <- get_eigenvalue(mca_tea)
head(eig.val)

fviz_screeplot(mca_tea, addlabels = TRUE, ylim = c(0, 45))

Next I tried biplot drawing, where individuals are in blue and variables in red. But this was too wild to make any real analysis. The distance between any row points or column points should give a measure of their similarity (or dissimilarity). Row points with similar profile are close on the factor map. The same holds true for column points. But anyway, one can see that for instance individuals 212 and 199 are very similar.

fviz_mca_biplot(mca_tea, 
                repel = TRUE, # Avoid text overlapping (slow if many point)
                ggtheme = theme_minimal())

The next plots identifies variables that are the most correlated with each dimension. The squared correlations between variables and the dimensions are used as coordinates. Where, how and price are most correlated with the dimansion 1 and friends and tea with dimension 2. Sugar is not actually correlating with either dimension.

fviz_mca_var(mca_tea, choice = "mca.cor", 
             repel = TRUE, # Avoid text overlapping (slow)
             ggtheme = theme_minimal())

Here similar variable categories are grouped toghether. Negative correlation is in opposite directions; for instance, p_private label and chain stroe+tea shop are negatively correlated

fviz_mca_var(mca_tea, col.var="black", shape.var = 15,
             repel = TRUE)

In the end I analyse, which top 20 variable categories contributes most to dimensions 1 and 2. Tea shop is contributing the second most in both dimensions. P_upscale is contributing over 15 % in dimension 1 and chainstore+tea shop abou 11 % in dimension 2.

fviz_contrib(mca_tea, choice = "var", axes = 1, top = 20)

fviz_contrib(mca_tea, choice = "var", axes = 2, top = 20)